using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;

namespace Rest.Transport
{
    /// <summary>
    /// Represents GET HTTP method
    /// </summary>
    public class GetRestTransport : RestTransport
    {
        private String commandText = String.Empty;

        /// <summary>
        /// 
        /// </summary>
        public String CommandText
        {
            get { return commandText; }
        }
  
        /// <summary>
        /// ctor
        /// </summary>
        public GetRestTransport()
        {
            HttpMethod = "GET";
            SupportsBody = false; 
        }

        /// <summary>
        /// Creates HttpWebRequest for a GET request
        /// </summary>
        /// <param name="serviceUri"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        protected sealed override HttpWebRequest CreateRequestCore(
            Uri serviceUri,
            RestParameterCollection parameters
        )
        {
            UriBuilder uriBuilder = new UriBuilder(serviceUri);

            // The serviceUri argument may have a query string: include parameters
            if (uriBuilder.Query != null)
            {
                parameters.Add(HttpUtility.ParseQueryString(uriBuilder.Query));  
            }

            StringBuilder paramStringBuilder = new StringBuilder();
            String key = null;

            if (parameters != null)
            {
                for (Int32 i = 0; i < parameters.Count; i++)
                {
                    key = parameters[i].Name;
                    paramStringBuilder.AppendFormat("{0}={1}",
                        HttpUtility.UrlEncode(key), 
                        HttpUtility.UrlEncode(parameters[i].Value));
                    if (i < parameters.Count - 1)
                        paramStringBuilder.Append("&");
                }
            }

            uriBuilder.Query = paramStringBuilder.ToString();

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uriBuilder.Uri);
            request.Method         = HttpMethod;
            request.ContentType    = HttpContentType.ContentType;

            commandText = uriBuilder.Uri.AbsoluteUri; 
            
            return request;
        }
    }
}
